package com.xjk.encryp;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ShaUtil {


    public static String encode512(String decrypt) {

        return encode(decrypt, "SHA-512");
    }

    public static String encode384(String decrypt){

        return encode(decrypt,"SHA-384");
    }

    public static String encode256(String decrypt) {

        return encode(decrypt, "SHA-256");
    }

    public static String encode(String decrypt) {

        return encode(decrypt, "SHA-1");
    }
    public static String encodeSHA512(String decrypt) {

        return encode(decrypt, "SHA-512");
    }

    public static String encodeSHA384(String decrypt){

        return encode(decrypt,"SHA-384");
    }

    public static String encodeSHA256(String decrypt) {

        return encode(decrypt, "SHA-256");
    }

    public static String encodeSHA(String decrypt) {

        return encode(decrypt, "SHA-1");
    }

    public static String encode(String decrypt, String type) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance(type);
            digest.update(decrypt.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (Exception e) {

        }
        return null;

    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static String generateHash(String data, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] hash = digest.digest(data.getBytes());
        return bytesToHex(hash);
    }

    public static void main(String[] args) {

        String newSign = ShaUtil.encode512("Hello, World!");
        System.out.println(newSign);
        System.out.println(encodeSHA512("Hello, World!"));
    }
}